<?php
/**
 * CDispatcher class file.
 * 发报器.
 * @author Huan Song <iphper@yeah.net>
 * @version $Id: CDispatcher.php 1 2011-02-26 09:19:06Z huan.song $
 * @package system.controller
 * @since 2.0
 */
class CDispatcher extends CApplication
{   
    /**
     * 实例化Controller类, 调用action方法.
     * <pre>
	 * $config = APP_DIR . '/config/main.php';
	 * $config = array();
	 * $config = null;
	 * 
	 * CDispatcher::run($config);
	 * </pre>
     * @throws CControllerException. 如果控制器类或方法不存在, 抛出异常.
     */
	public static function run($config = null)
	{	
		CConfig::set($config);
		set_exception_handler(CControllerConfig::getErrorAction());
		require_once CControllerConfig::getControllerFile();
		$controllerClass = CControllerConfig::getControllerClass();
		if (class_exists($controllerClass)) 
		{
			$class = new $controllerClass();
			if ($class instanceof CController) 
			{
				$method = CControllerConfig::getActionMethod();
				if (method_exists($class, $method)) 
				{
					$class->preAction();
					$class->$method();
					$class->postAction();
				}
				else 
					throw new CControllerException('CDispatcher:run action method not exists', array('{method}' => $method));
			}
			else 
				throw new CControllerException('CDispatcher:run controller class not instanceof CController', array('{controllerClass}' => $controllerClass));
		}
		else 
			throw new CControllerException('CDispatcher:run controllerClass not exists', array('{controllerClass}' => $controllerClass));
	}
}
